package com.springboot_activiti.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.springboot_activiti.service.ActivityConsumerService;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/activiti")
public class ActivitiController {

     @Autowired
     private ActivityConsumerService activityConsumerService;
    @Autowired
    private RepositoryService repositoryService;

     /**
      * 注册流程
      * @return
     */
    @RequestMapping(value = "deploy")
    public boolean deploy(String modelId, RedirectAttributes redirectAttributes) {
        try {
            Model modelData = repositoryService.getModel(modelId);
            ObjectNode modelNode = (ObjectNode) new ObjectMapper()
                    .readTree(repositoryService.getModelEditorSource(modelData.getId()));
            byte[] bpmnBytes = null;

            BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
            bpmnBytes = new BpmnXMLConverter().convertToXML(model);

            String processName = modelData.getName() + ".bpmn20.xml";
            Deployment deployment = repositoryService.createDeployment().key(modelData.getName())
                    .name(modelData.getName()).addString(processName, new String(bpmnBytes,"UTF-8"))
                    .deploy();
            redirectAttributes.addFlashAttribute("message", "部署成功，部署ID=" + deployment.getId());
            System.out.println("部署成功，部署ID=" + deployment.getId());
        } catch (Exception e) {
            System.out.println("根据模型部署流程失败：modelId="+ modelId);
            return false;
        }
        return true;
    }

    /**
     * 启动流程
     * @return
     */
    @RequestMapping("/startActivityDemo")
    public String startActivityDemo(String modelKey,String user,Integer days){
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("appoveUser",user);
        dataMap.put("days",days);
        dataMap.put("groupLeader","hxm001");
        dataMap.put("companyLeader","hxm002");
        return activityConsumerService.startActivityDemo(modelKey,dataMap);
    }

    /**
     * 获取待办
     * @return
     */
    @RequestMapping("/getTaskList")
    public boolean getTaskList(String userId){
        return activityConsumerService.getTaskList(userId);
    }

    /**
     * 提交
     * @param taskId
     * @return
     */
    @RequestMapping("/complete")
    public boolean complete(String taskId,String result){
        Map<String,Object> dataMap = new HashMap<>();
        if("1".equals(result)){
            dataMap.put("flag",true);
        }else{
            dataMap.put("flag",false);
        }
        return activityConsumerService.complete(taskId);
    }
    /**
     * 根据流程id直接结束流程
     * @paramru
     * @return
     */
    @RequestMapping("/deleteProcessInstance")
    public boolean deleteProcessInstance(String runId){
        return activityConsumerService.deleteProcessInstance(runId);
    }


    /**
     * 查询已经部署的模板
     * @return
     */
    @RequestMapping("/deploymentList")
    public boolean deploymentList() {
        //查询部署
        List<Deployment> deployments = repositoryService.createDeploymentQuery()
                .orderByDeploymenTime().asc()
                .list();

        for (Deployment deployment:deployments){
            System.out.println(deployment);
        }
        System.out.println(deployments.size());

        return true;
    }
}
